package com.guigui.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guigui.common.constant.ProductConstant;
import com.guigui.common.dto.elastic.SkusElasticModel;
import com.guigui.common.to.CouponSaveTo;
import com.guigui.common.to.MemberPriceTo;
import com.guigui.common.to.ware.WareStockVo;
import com.guigui.common.utils.PageUtils;
import com.guigui.common.utils.Query;
import com.guigui.common.utils.R;
import com.guigui.gulimall.product.dao.SpuInfoDao;
import com.guigui.gulimall.product.dto.spuinfo.*;
import com.guigui.gulimall.product.entity.*;
import com.guigui.gulimall.product.feign.CouponFeignService;
import com.guigui.gulimall.product.feign.SearchFeignService;
import com.guigui.gulimall.product.feign.WareFeignService;
import com.guigui.gulimall.product.service.*;
import com.guigui.gulimall.product.to.SpuBoundsTo;
import com.mysql.cj.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;


/**
 * @author xin
 */
@Service("spuInfoService")
@Slf4j
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    private SpuInfoDescService spuInfoDescService;

    @Autowired
    private AttrService attrService;

    @Autowired
    private SpuImagesService spuImagesService;

    @Autowired
    private ProductAttrValueService productAttrValueService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private SkuInfoService skuInfoService;

    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private CouponFeignService couponFeignService;

    @Autowired
    private BrandService brandService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private WareFeignService wareFeignService;

    @Autowired
    private SearchFeignService searchFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 级联保存商品信息<br/>
     * 跨gulimall_pms，gulimall_sms两库及多张表 <br/>
     * TODO 分布式事务待解决
     * @param spuDto
     */
    @Transactional(rollbackFor = Throwable.class)
    @Override
    public void saveSpuDto(SpuSaveDto spuDto) {
        // 1.保存spu基本信息 pms_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuDto, spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.saveBaseSpuInfo(spuInfoEntity);

        // 2.保存spu图片信息 pms_spu_images
        List<String> imagesUrl = spuDto.getImages();
        spuImagesService.saveImages(spuInfoEntity.getId(), imagesUrl);

        // 3.保存spu描述信息 pms_spu_info_desc
        List<String> descriptionUrl = spuDto.getDescript();
        SpuInfoDescEntity spuDescEntity = new SpuInfoDescEntity();
        spuDescEntity.setSpuId(spuInfoEntity.getId());
        spuDescEntity.setDecript(String.join(",", descriptionUrl));
        spuInfoDescService.save(spuDescEntity);

        // 4.保存spu规格参数 pms_product_attr_value
        List<BaseAttrs> baseAttrs = spuDto.getBaseAttrs();
        List<ProductAttrValueEntity> productAttrValueEntities = baseAttrs.stream().map(attrs -> {
            ProductAttrValueEntity productAttrValue = new ProductAttrValueEntity();
            productAttrValue.setAttrName("");
            AttrEntity attrEntity = attrService.getById(attrs.getAttrId());
            if (attrEntity != null) {
                productAttrValue.setAttrName(attrEntity.getAttrName());
            }

            productAttrValue.setQuickShow(attrs.getShowDesc());
            productAttrValue.setAttrId(attrs.getAttrId());
            productAttrValue.setAttrValue(attrs.getAttrValues());
            productAttrValue.setSpuId(spuInfoEntity.getId());

            return productAttrValue;
        }).collect(Collectors.toList());
        productAttrValueService.saveBatch(productAttrValueEntities);
        // 5.保存积分信息 gulimall_sm库中的sms_spu_bounds表
        // 5.保存sku信息
        List<Skus> skusList = spuDto.getSkus();
        if (skusList != null && skusList.size() > 0) {

            skusList.forEach(sku -> {
                // 1.保存pms_sku_info
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                List<Images> skuImages = sku.getImages();

                // 找出并设置默认图片url
                skuImages.forEach(images -> {
                    if (images.getDefaultImg() == 1 && !"".equals(images.getImgUrl())) {
                        skuInfoEntity.setSkuDefaultImg(images.getImgUrl());
                    }

                });
                BeanUtils.copyProperties(sku, skuInfoEntity);
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setCatalogId(spuDto.getCatalogId());
                skuInfoEntity.setBrandId(spuDto.getBrandId());
                skuInfoService.save(skuInfoEntity);
                sku.setSkuId(skuInfoEntity.getSkuId());

                // 保存pms_sku_images信息
                List<SkuImagesEntity> skuImagesEntities = skuImages.stream().map(images -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    if (!"".equals(images.getImgUrl())) {
                        BeanUtils.copyProperties(images, skuImagesEntity);
                        skuImagesEntity.setSkuId(skuInfoEntity.getSkuId());
                        return skuImagesEntity;
                    } else {
                        return null;
                    }
                }).filter(Objects::nonNull).collect(Collectors.toList());
                skuImagesService.saveBatch(skuImagesEntities);

                // 保存pms_sku_sale_attr_value信息
                List<Attr> attrs = sku.getAttr();
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attrs.stream().map(attr -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(attr, skuSaleAttrValueEntity);
                    skuSaleAttrValueEntity.setSkuId(skuInfoEntity.getSkuId());
                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);
            });

        }


        // 5.保存积分信息 gulimall_sms表
        // 5.1保存商品阶梯价格信息 sms_sku_ladder
        // 5.2保存满减信息 sms_sku_full_reduction
        // 5.2保存sku图片信息 pms_sku_images
        // 5.3保存sku销售属性信息 pms_sku_sale_attr_value
        // 5.4保存sku优惠满减信息gulimall_sms库中的表
        Bounds bounds = spuDto.getBounds();
        SpuBoundsTo spuBoundsTo = new SpuBoundsTo().setSpuId(spuInfoEntity.getId()).setBuyBounds(bounds.getBuyBounds()).setGrowBounds(bounds.getGrowBounds());
        R r = couponFeignService.saveBounds(spuBoundsTo);
        if (r.getCode() != 0) {
            log.error("远程保存积分信息失败");
        }

        List<CouponSaveTo> couponSaveToList = skusList.stream().map(sku -> {
            CouponSaveTo couponSaveTo = new CouponSaveTo();
            List<MemberPrice> memberPriceList = sku.getMemberPrice();

            List<MemberPriceTo> memberPriceTos = memberPriceList.stream().map(m -> {
                return new MemberPriceTo().setSkuId(spuInfoEntity.getId()).setMemberPrice(m.getPrice()).setMemberLevelId(m.getId()).setMemberLevelName(m.getName());
            }).collect(Collectors.toList());
            couponSaveTo.setMemberPriceTos(memberPriceTos);
            BeanUtils.copyProperties(sku, couponSaveTo);
            return couponSaveTo;
        }).collect(Collectors.toList());
        r = couponFeignService.saveReductionLadderMemberPrice(couponSaveToList);
        if (r.getCode() != 0) {
            log.error("远程保存满减、会员价格等信息失败");
        }
    }

    @Override
    public void saveBaseSpuInfo(SpuInfoEntity spuInfoEntity) {
        this.save(spuInfoEntity);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> queryWrapper = new QueryWrapper<>();

        String brandId = (String) params.get("brandId");
        if (!StringUtils.isNullOrEmpty(brandId) && !"0".equals(brandId)) {
            queryWrapper.eq("brand_id", Long.valueOf(brandId));
        }

        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isNullOrEmpty(catelogId) && !"0".equals(catelogId)) {
            queryWrapper.eq("catalog_id", Long.valueOf(catelogId));
        }

        String status = (String) params.get("status");
        if (!StringUtils.isNullOrEmpty(status)) {
            queryWrapper.eq("publish_status", Integer.valueOf(status));
        }

        String key = (String) params.get("key");
        if (!StringUtils.isNullOrEmpty(key)) {
            queryWrapper.and(q -> {
                q.eq("id", key).or().like("spu_name", key);
            });
        }

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void up(Long spuId) {

        List<SkuInfoEntity> skuInfoEntities = skuInfoService.selectBySpuId(spuId);

        // 0 先查出品牌名，品牌图片
        BrandEntity brand = brandService.getById(skuInfoEntities.get(0).getBrandId());

        // 1 同理，查出分类名
        CategoryEntity category = categoryService.getById(skuInfoEntities.get(0).getCatalogId());

        // 3 同理查出attr属性
        List<ProductAttrValueEntity> productAttrValueEntities = productAttrValueService.listBySpu(spuId);

        List<Long> productAttrValueAttrIdCollect = productAttrValueEntities.stream().map(ProductAttrValueEntity::getAttrId).collect(Collectors.toList());

        // 可以被搜索的attrIds，并转换为set
        List<Long> canSearchAttrIds = attrService.selectSearchAttrIds(productAttrValueAttrIdCollect);
        Set<Long> canSearchAttrIdsSet = new HashSet<>(canSearchAttrIds);

        // 过滤出能为搜索的索引，映射为Attrs集合
        List<SkusElasticModel.Attrs> attrs = productAttrValueEntities.stream().filter(p -> canSearchAttrIdsSet.contains(p.getAttrId())).map(p -> {
            SkusElasticModel.Attrs attr = new SkusElasticModel.Attrs();
            attr.setAttrId(p.getAttrId()).setAttrValue(p.getAttrValue()).setAttrName(p.getAttrName());
            return attr;
        }).collect(Collectors.toList());

        // 远程调用，是否有库存
        Map<Long, Boolean> stockMap = null;
        try {
            List<Long> skuIds = skuInfoEntities.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
            List<WareStockVo> hasStock = wareFeignService.hasStock(skuIds);
            // 转换为库存map，key为skuId，value为库存boolean值
            stockMap = hasStock.stream().collect(Collectors.toMap(WareStockVo::getSkuId, WareStockVo::getStock));
        } catch (Exception e) {
            log.info("SpuInfoServiceImpl 查询库存服务调用失败");
        }

        // 属性映射为SkusElasticModel集合，传给search服务
        Map<Long, Boolean> finalStockMap = stockMap;
        List<SkusElasticModel> elasticModels = skuInfoEntities.stream().map(sku -> {
            SkusElasticModel elasticModel = new SkusElasticModel();
            BeanUtils.copyProperties(sku, elasticModel);

            elasticModel.setSkuPrice(sku.getPrice());
            elasticModel.setSkuImg(sku.getSkuDefaultImg());

            // 库存map查结果
            elasticModel.setHasStock(finalStockMap == null || finalStockMap.getOrDefault(sku.getSkuId(), false));
            // 热度评分
            elasticModel.setHotScore(0L);
            // 一个spu只会有一个对应的品牌，所以在上面 0 先查出来
            elasticModel.setBrandName(brand.getName()).setBrandImg(brand.getLogo());
            // 分类名, 1 先查出来
            elasticModel.setCatalogName(category.getName());
            // 可查询的参数即属性
            elasticModel.setAttrs(attrs);

            return elasticModel;
        }).collect(Collectors.toList());

        R status = searchFeignService.productSaveAndUp(elasticModels);

        if (status.getCode() == 0) {
            this.baseMapper.productUp(spuId, ProductConstant.PublishStatus.PRODUCT_UP.getCode());
        }
        // TODO 重复上架 引申出幂等性问题
    }

}